package csu.web.jpetstore.web.servlet;

import com.alibaba.fastjson.JSON;
import csu.web.jpetstore.domain.Cart;
import csu.web.jpetstore.domain.CartItem;
import csu.web.jpetstore.persistence.impl.LoggerDAOImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Iterator;

import static csu.web.jpetstore.persistence.impl.LoggerDAOImpl.loginLogger;

public class UpdateCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();

        Cart cart = (Cart) session.getAttribute("cart");
        //此处可判断，cart是否为null，是，则不可访问update
        if (cart==null)
            req.getRequestDispatcher(CART_FORM).forward(req,resp);
        Iterator<CartItem> cartItems = cart.getAllCartItems();

        LoggerDAOImpl loggerDAO=new LoggerDAOImpl();
        loginLogger.setStarttime();
        loginLogger.setAction(loginLogger.getUsername()+"刷新购物车");
        try {
            loggerDAO.logger(loginLogger);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                String quantityString = req.getParameter(itemId);
                int quantity = Integer.parseInt(quantityString);

                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {
                //ignore parse exceptions on purpose
            }
        }

        String result= JSON.toJSONString(cartItems);
        System.out.println(result);
        req.getRequestDispatcher(CART_FORM).forward(req,resp);

        resp.setContentType("text/json");
        PrintWriter out=resp.getWriter();
        out.println(result);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}